package com.atguigu.edu.controller;


import com.atguigu.common.util.R;
import com.atguigu.edu.entity.EduTeacher;
import com.atguigu.edu.entity.vo.query.EduTeacherQuery;
import com.atguigu.edu.service.EduTeacherService;
import com.atguigu.service.base.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author alexzshl
 * @since 2021-04-30
 */
@RestController
@RequestMapping("/api/edu/teacher")
@Api("TeacherController 控制类")
@CrossOrigin
// @CrossOrigin(origins = {
//         "http://localhost:5500",
//         "http://localhost:9528",
//         "http://127.0.0.1:5500",
//         "http://127.0.0.1:9528",
// })
public class EduTeacherController {

    @Resource
    private EduTeacherService eduTeacherService;

    // @ApiOperation("查询所有讲师")
    // @GetMapping("/findAll")
    // public List<Teacher> findAll() {
    //     return teacherService.list(null);
    // }
    //
    // @DeleteMapping("/delete/{id}")
    // // @RequestMapping("/delete/{id}")
    // @ApiOperation("根据 id 删除讲师（逻辑删除）")
    // public Boolean removeById(
    //         @ApiParam(name = "id", value = "讲师id", required = true)
    //         @PathVariable(name = "id") String id) {
    //     return teacherService.removeById(id);
    // }

    @RequestMapping("/")
    public Object index() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("service-name", "/api/edu/teacher");
        result.put("success", "ok");
        return result;
    }

    @ApiOperation("查询所有讲师 - 返回统一数据格式")
    @GetMapping(value = {"/list", "list"})
    public R listAll() {
        List<EduTeacher> data = eduTeacherService.list(null);

        // ResponseMessage respMsg = new ResponseMessage();
        // respMsg
        //         .setSuccess(true)
        //         .setCode(200)
        //         .setMessage("test")
        //         .setData(new ResponseData(data.size(), data));
        //
        // HashMap<String, Object> dataWrapper = new HashMap<>();
        // dataWrapper.put("total", data.size());
        // dataWrapper.put("rows", data);
        // R2.ok().data(dataWrapper);
        // return respMsg;

        return R.ok().data("items", data).data("teacherList", data).data("rows", data).data("list", data);
    }



    @GetMapping("/page-limit/{current}/{limit}")
    @ApiOperation("分页查询")
    public R getPage(
            @ApiParam(name = "current", value = "当前页", required = true)
            @PathVariable("current")
                    Integer current,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable("limit") Integer size) {
        Page<EduTeacher> page = new Page<>(current, size);
        eduTeacherService.page(page, null);

        long total = page.getTotal();
        List<EduTeacher> records = page.getRecords();
        return R.ok().data("total", total).data("rows", records);

        // HashMap<String, Object> data = new HashMap<>();
        // data.put("total", total);
        // data.put("rows", records);
        // return R2.ok().data(data);
    }

    // @RequestMapping(value = "/page-condition/{current}/{limit}", method = {RequestMethod.GET})
    @GetMapping("/page-get/{current}/{limit}")
    @ApiOperation("多条件组合查询带分页-GET方式")
    public R pageTeacherCondition(
            @ApiParam(name = "current", value = "当前页", required = true)
            @PathVariable("current")
                    Integer current,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable("limit") Integer limit,
            EduTeacherQuery query) {
        System.out.println(current);
        System.out.println(limit);
        System.out.println(query);

        Page<EduTeacher> page = new Page<>(current, limit);
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<EduTeacher>();

        // String name = query.getName();
        // Integer level = query.getLevel();
        // String begin = query.getBegin();
        // String end = query.getEnd();
        // if (!StringUtils.isEmpty(name)) {
        //     wrapper.like("name", name);
        // }
        // if (!StringUtils.isEmpty(level)) {
        //     wrapper.eq("level", level);
        // }
        // if (!StringUtils.isEmpty(begin)) {
        //     wrapper.ge("gem_create", begin);
        // }
        // if (!StringUtils.isEmpty(end)) {
        //     wrapper.le("gem_create", end);
        // }

        // 也可以使用 Wrapper 中带 Condition 的方法
        wrapper
                .like(!StringUtils.isEmpty(query.getName()), "name", query.getName())
                .eq(!StringUtils.isEmpty(query.getLevel()), "level", query.getLevel())
                .ge(!StringUtils.isEmpty(query.getBegin()), "gmt_create", query.getBegin())
                .le(!StringUtils.isEmpty(query.getEnd()), "gmt_create", query.getEnd());

        eduTeacherService.page(page, wrapper);

        long total = page.getTotal();
        List<EduTeacher> records = page.getRecords();
        return R.ok().data("total", total).data("items", records);
    }

    // @RequestMapping(value = "/page-condition-v2/{current}/{limit}", method = {RequestMethod.POST})
    @PostMapping("/page/{current}/{limit}")
    @ApiOperation("多条件组合查询带分页-POST方式")
    public R pageTeacherConditionV2(
            @ApiParam(name = "current", value = "当前页", required = true)
            @PathVariable("current") Integer current,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable("limit") Integer size,
            @RequestBody(required = false) EduTeacherQuery query) {
        Page<EduTeacher> page = new Page<>(current, size);
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<EduTeacher>();

        wrapper
                .like(!StringUtils.isEmpty(query.getName()), "name", query.getName())
                .eq(!StringUtils.isEmpty(query.getLevel()), "level", query.getLevel())
                .ge(!StringUtils.isEmpty(query.getBegin()), "gmt_create", query.getBegin())
                .le(!StringUtils.isEmpty(query.getEnd()), "gmt_create", query.getEnd())
                .orderByDesc("gmt_create");

        eduTeacherService.page(page, wrapper);

        long total = page.getTotal();
        List<EduTeacher> records = page.getRecords();
        return R.ok().data("total", total).data("items", records);
    }

    @ApiOperation("根据id查询讲师")
    @GetMapping("/get/{id}")
    public R getTeacher(@PathVariable("id") String id) {
        EduTeacher eduTeacher = eduTeacherService.getById(id);
        return R.ok().data("result", eduTeacher);
    }

    @ApiOperation("添加讲师")
    @PostMapping("/add")
    public R addTeacher(@RequestBody(required = true) EduTeacher eduTeacher) {
        System.out.println(eduTeacher);
        boolean save = eduTeacherService.save(eduTeacher);
        return save ? R.ok().message("添加成功") : R.error().message("添加失败");
    }

    @DeleteMapping("/delete/{id}")
    // @RequestMapping("/delete/{id}")
    @ApiOperation("根据 id 删除讲师（逻辑删除）- 返回统一数据格式")
    public R removeByIdV2(
            @ApiParam(name = "id", value = "讲师id", required = true)
            @PathVariable(name = "id") String id) {
        Boolean result = eduTeacherService.removeById(id);
        if (result) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    /**
     * 如何更新局部字段 或者 只更新传入的非空字段？
     * 如果前端只传了 Model 的部分字段，那么mvc收集到的其他字段为 0/null
     * 如果是使用 jdbc，直接更新会修改未传入的字段（置空），此时需要使用 @ModelAttribute 注解加在 get 方法上（此方法相当于Model前置处理器）
     * 如果是使用 mybatis-plus，会自动帮我们进行数据库字段回传，相当于默认就是只更新传入的字段
     * @param eduTeacher
     * @return
     */
    @PostMapping("/update")
    public R updateTeacher(@RequestBody EduTeacher eduTeacher) {
        System.out.println(eduTeacher);
        EduTeacher source = eduTeacherService.getById(eduTeacher.getId());
        boolean update = eduTeacherService.updateById(eduTeacher);
        EduTeacher target = eduTeacherService.getById(eduTeacher.getId());
        if (update) {
            return R.ok().message("修改成功").data("source", source).data("target", target);
        } else {
            return R.error().message("修改失败").data("source", source).data("target", target);
        }
    }

    /**
     * put 一般是做完整更新
     * @param eduTeacher
     * @return
     */
    @PutMapping("/update-put")
    public R updateTeacherPut(@RequestBody EduTeacher eduTeacher) {
        System.out.println(eduTeacher);
        EduTeacher source = eduTeacherService.getById(eduTeacher.getId());
        boolean update = eduTeacherService.updateById(eduTeacher);
        EduTeacher target = eduTeacherService.getById(eduTeacher.getId());;
        if (update) {
            return R.ok().message("修改成功").data("source", source).data("target", target);
        } else {
            return R.error().message("修改失败").data("source", source).data("target", target);
        }
    }





    @GetMapping("/test/exception")
    public R testException() {
        int i = 10 / 0;
        return R.ok();
    }

    @GetMapping("/test/exception/guli")
    public R testGuliException() {
        if (2 > 1) {
            throw  new GuliException(50001, "数据库解析异常");
        }
        return R.ok();
    }
}

